# -*- coding: utf-8 -*-
#
# Copyright 2007-2013 Luciano Xumerle. All rights reserved.
# Luciano Xumerle <luciano.xumerle@gmail.com>
#
# This file is part of cnxrename.
#
# Cnxrename is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Cnxrename is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cnxrename.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
reload(sys)

class CDDB:
	"""Classe per gestire file di testo"""

	GENRE = {
	"Blues" : 0,
	"Classic Rock" : 1,
	"Country" : 2,
	"Dance" : 3,
	"Disco" : 4,
	"Funk" : 5,
	"Grunge" : 6,
	"Hip-Hop" : 7,
	"Jazz" : 8,
	"Metal" : 9,
	"New Age" : 10,
	"Oldies" : 11,
	"Other" : 12,
	"Pop" : 13,
	"R&B" : 14,
	"Rap" : 15,
	"Reggae" : 16,
	"Rock" : 17,
	"Techno" : 18,
	"Industrial" : 19,
	"Alternative" : 20,
	"Ska" : 21,
	"Death Metal" : 22,
	"Pranks" : 23,
	"Soundtrack" : 24,
	"Euro-Techno" : 25,
	"Ambient" : 26,
	"Trip-Hop" : 27,
	"Vocal" : 28,
	"Jazz&Funk" : 29,
	"Fusion" : 30,
	"Trance" : 31,
	"Classical" : 32,
	"Instrumental" : 33,
	"Acid" : 34,
	"House" : 35,
	"Game" : 36,
	"Sound Clip" : 37,
	"Gospel" : 38,
	"Noise" : 39,
	"Alternative Rock" : 40,
	"Bass" : 41,
	"Soul" : 42,
	"Punk" : 43,
	"Space" : 44,
	"Meditative" : 45,
	"Instrumental Pop" : 46,
	"Instrumental Rock" : 47,
	"Ethnic" : 48,
	"Gothic" : 49,
	"Darkwave" : 50,
	"Techno-Industrial" : 51,
	"Electronic" : 52,
	"Pop-Folk" : 53,
	"Eurodance" : 54,
	"Dream" : 55,
	"Southern Rock" : 56,
	"Comedy" : 57,
	"Cult" : 58,
	"Gangsta" : 59,
	"Top 40" : 60,
	"Christian Rap" : 61,
	"Pop/Funk" : 62,
	"Jungle" : 63,
	"Native US" : 64,
	"Cabaret" : 65,
	"New Wave" : 66,
	"Psychedelic" : 67,
	"Rave" : 68,
	"Showtunes" : 69,
	"Trailer" : 70,
	"Lo-Fi" : 71,
	"Tribal" : 72,
	"Acid Punk" : 73,
	"Acid Jazz" : 74,
	"Polka" : 75,
	"Retro" : 76,
	"Musical" : 77,
	"Rock & Roll" : 78,
	"Hard Rock" : 79,
	"Folk" : 80,
	"Folk-Rock" : 81,
	"National Folk" : 82,
	"Swing" : 83,
	"Fast Fusion" : 84,
	"Bebop" : 85,
	"Latin" : 86,
	"Revival" : 87,
	"Celtic" : 88,
	"Bluegrass" : 89,
	"Avantgarde" : 90,
	"Gothic Rock" : 91,
	"Progressive Rock" : 92,
	"Psychedelic Rock" : 93,
	"Symphonic Rock" : 94,
	"Slow Rock" : 95,
	"Big Band" : 96,
	"Chorus" : 97,
	"Easy Listening" : 98,
	"Acoustic" : 99,
	"Humour" : 100,
	"Speech" : 101,
	"Chanson" : 102,
	"Opera" : 103,
	"Chamber Music" : 104,
	"Sonata" : 105,
	"Symphony" : 106,
	"Booty Bass" : 107,
	"Primus" : 108,
	"Porn Groove" : 109,
	"Satire" : 110,
	"Slow Jam" : 111,
	"Club" : 112,
	"Tango" : 113,
	"Samba (Musik)" : 114,
	"Folklore" : 115,
	"Ballad" : 116,
	"Power Ballad" : 117,
	"Rhytmic Soul" : 118,
	"Freestyle" : 119,
	"Duet" : 120,
	"Punk Rock" : 121,
	"Drum Solo" : 122,
	"Acapella" : 123,
	"Euro-House" : 124,
	"Dance Hall" : 125,
	"Goa" : 126,
	"Drum'n'Bass" : 127,
	"Club-House" : 128,
	"Hardcore" : 129,
	"Terror" : 130,
	"Indie" : 131,
	"BritPop" : 132,
	"Negerpunk" : 133,
	"Polsk Punk" : 134,
	"Beat" : 135,
	"Christian Gangsta" : 136,
	"Heavy Metal" : 137,
	"Black Metal" : 138,
	"Crossover" : 139,
	"Contemporary Christian" : 140,
	"Christian Rock" : 141,
	"Merengue" : 142,
	"Salsa" : 143,
	"Thrash Metal" : 144,
	"Anime" : 145,
	"JPop" : 146,
	"SynthPop" : 147
	}

	artist=""
	album=""
	year=""

	songs=[]
	cd=[]
	destination=[]

	showArtist=False
	isFileOK=True

	isLengthMajor30=False

	def __init__(self,file,mode):
		self.showArtist = mode
		fout = open(file, "r")
		for line in open(file, "r"):
			# process each line (whatever you need)
			# for example ...
			process = line.strip()
			if len(process) == 0:
				continue;
			isCDNUM = process.find( "-- CD" ) > -1
			if self.artist == "":
				firstbar = process.find("::")
				if firstbar == -1:
					firstbar = process.find( "/");

				if firstbar > 0:
					oround = process.rfind( "(" )
					cround = process.rfind( ")" )
					self.artist = process[0:firstbar].strip()
					self.year = process[ oround + 1:cround ]
					if len(self.year) == 4 and self.year.isdigit():
						self.album = process[ firstbar + 1 : oround - 1 ].strip()
						if(self.album[0] == ":"):
							self.album = self.album[1:].strip()
					else:
						self.year = ""
						self.album = process[ firstbar + 1 : ].strip()
				else:
					self.isFileOK = False
			elif isCDNUM:
				self.cd.append( len(self.songs) + 1 )
			else:
				dot = process.find( "." );
				if dot > -1 and process[ :dot ].isdigit():
					process = process[ dot + 1: ].strip()
					# check for song duration at start of line
					dots = process.find( ":" )
					spc = process.find( " " )
					if dots > -1 and spc > -1 and spc > dots and process[ :dots ].isdigit() and process[ dots + 1:spc ].isdigit():
						process=process[ spc + 1: ].strip()
					self.songs.append( process )
		self.setDestination()
		fout.close()


	def setDestination(self):
		songcounter = 1
		cdcounter = 0
		for i in range(len(self.songs)):
			temp = ""
			counter = i + 1
			if len(self.cd) > 0:
				for h in range(len(self.cd)):
					if self.cd[h] == counter:
						cdcounter+=1
						songcounter = 1

			if songcounter < 10:
				temp = "0"
			temp += str(songcounter) + "-"

			if cdcounter > 0:
				temp = str(cdcounter) + temp
				if len(self.cd)>9 and cdcounter<10:
					temp= '0' + temp

			# ADD SONG ARTIST IF REQUIRED
			if self.showArtist:
				temp += self.getSongArtist(i) + "-"

			# ADD SONG TITLE
			temp += self.getSongTitle(i)

			self.destination.append( temp )
			songcounter+=1


	def getDestination( self, position ):
		return self.destination[position-1]


	def toString(self):
		cdcounter = 0
		pp = " " + self.artist + " / " + self.album + " (" + str(self.year) + ")\n\n"
		for i in range(len(self.songs)):
			j = i + 1
			if len(self.cd) > 0:
				for h in range(len(self.cd)):
					if self.cd[ h ] == j:
						cdcounter+=1
						pp += "\n -- CD" + str( cdcounter ) + ":\n"

			if j < 10:
				pp += " "
			pp += " " + str( j ) + ". " + self.songs[ i ] + "\n";
		return pp;

	def getArtist(self):
		return self.artist

	def getAlbum(self):
		return self.album

	def getYear(self):
		return self.year

	def getSongNumber(self):
		return len(self.songs)

	def isFileOK(self):
		return self.isFileOK and len(self.songs) > 0

	def printCUE(self, files):
		if len(files) != self.getSongNumber():
			return False
		print self.getCUEheader()
		cc = 0
		for i in range(len(files)):
			print 'FILE "' + files[ i ].getFile() + '" WAVE'
			print self.getCUEsong( cc )
			print 'INDEX 01 00:00:00'
			cc+=1
		return True


	def getDestDir( self ):
		rymtxt = self.artist + ' - ' + self.album + ' (' + self.year + ')'
		return rymtxt.replace(r'/', r'&')


	def getCUEheader(self):
		return "PERFORMER \"" + self.artist + "\"\nTITLE \"" + self.album + "\"\n"


	def getSongArtist(self, i):
		aa = self.artist
		dots = self.songs[ i ].find( "::" )
		if dots > -1:
			aa =  self.songs[ i ][ :dots ].strip()
		return aa


	def getSongTitle(self, i):
		bb=self.songs[ i ]
		dots = bb.find( "##" )
		if dots > -1:
			bb = bb[ :dots ]
		dots = bb.find( "::" )
		if dots > -1:
			bb = bb[ dots + 2: ]
		return bb.strip()


	def getSongComment(self, i):
		bb=""
		dots = self.songs[ i ].find( "##" )
		if dots > -1:
			bb = self.songs[ i ][ dots + 2: ].strip()
		return bb


	def getCUEsong(self, i ):
		ss = i + 1
		out=""
		# print results
		if ss < 10:
			out = "  TRACK 0" + str( ss ) + " AUDIO\n"
		else:
			out = "  TRACK " + str( ss ) + " AUDIO\n"
		out += "    PERFORMER \"" + self.getSongArtist(i) + "\"\n"
		out += "    TITLE \"" + self.getSongTitle(i) + '"'
		return out


	def tagger( self, files ):
		self.checkMajor30()
		if len(files)==len(self.songs):
			genre=self.askForGENRE()
			for i in range(len(self.songs)):
				print "TAGGING FILE: " + files[i].getSrcFile() + "\n"
				if files[i].getSrcFile().rfind('.mp3')>0:
					self.tagMP3( files[i].getSrcFile(), i, genre )
				elif files[i].getSrcFile().rfind('.ogg')>0:
					self.tagOGG( files[i].getSrcFile(), i, genre )


	def tagMP3( self, file, index, genreNumber ):
		from mutagen.easyid3 import EasyID3
		import mutagen.id3
		try:
			audio = EasyID3(file)
			audio.delete()
		except mutagen.id3.ID3NoHeaderError:
			audio = EasyID3()
		audio["artist"] = self.getSongArtist(index)
		audio["title"] = self.getSongTitle(index)
		audio["album"] = self.album
		audio["date"] = str(self.year)
		audio["tracknumber"] = str( index + 1 ) + '/' +  str(len(self.songs))
		audio["genre"] = str(genreNumber)
		audio.save(file)


	def tagOGG( self, file, index, genreNumber ):
		from mutagen.oggvorbis import OggVorbis
		audio = OggVorbis(file)
		audio.delete()
		audio["artist"] = self.getSongArtist(index)
		audio["title"] = self.getSongTitle(index)
		audio["album"] = self.album
		audio["date"] = str(self.year)
		audio["tracknumber"] = str( index + 1 ) + '/' +  str(len(self.songs))
		audio["genre"] = self.getGENRE(genreNumber)
		audio.save()


	def getGENRE( self, number ):
		for k in sorted(self.GENRE.keys()):
			if self.GENRE[k]==number:
				return k


	def askForGENRE( self ):
		counter = 0
		line=""
		for k in sorted(self.GENRE.keys()):
			if counter == 4:
				counter=0
				print line
				line=""
			rr=' ' + str(self.GENRE[k]) + ':' + k + '                         '
			line+=rr[:24]
			counter=counter+1
		print line
		print "INSERT GENRE NUMBER [0..147]: "
		numero = -1
		while numero < 0 or numero > len(self.GENRE):
			try:
				numero = int(sys.stdin.readline())
			except ValueError:
				numero=-1
		return numero


	def checkMajor30(self):
		if self.isLengthMajor30:
			return
		if(len(self.album)>30 or len(self.artist)>30):
			self.isLengthMajor30=True
		else:
			for i in range(len(self.songs)):
				if not self.isLengthMajor30 and (len(self.getSongArtist(i))>30 or len(self.getSongTitle(i))>30):
						self.isLengthMajor30=True

